package tsou.com.simple.realmtest;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.List;

import io.realm.OrderedRealmCollectionSnapshot;
import io.realm.Realm;
import io.realm.RealmAsyncTask;
import io.realm.RealmResults;
import tsou.com.simple.realmtest.adapter.MyAdapter;
import tsou.com.simple.realmtest.bean.Men;
import tsou.com.simple.realmtest.utils.UIUtils;

public class UpdataActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

    private ListView mListview;
    private List<String> titles = new ArrayList<>();
    private Realm mRealm;
    private RealmAsyncTask realmAsyncTask;

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (realmAsyncTask != null && !realmAsyncTask.isCancelled()) {
            realmAsyncTask.cancel();
        }
        if (mRealm != null && !mRealm.isClosed()) {
            mRealm.close();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        mRealm = UIUtils.getRealmInstance();
        initData();
        initView();
        initListener();
    }

    private void initData() {
        titles.add("同步操作：executeTransaction修改");
        titles.add("异步操作：executeTransactionAsync修改");
        titles.add("重要：使用查询语句得到数据，然后将内容修改");
    }

    private void initView() {
        mListview = (ListView) findViewById(R.id.listview);

        mListview.setAdapter(new MyAdapter(this, titles));
    }

    private void initListener() {
        mListview.setOnItemClickListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        switch (position) {
            default:
                break;
            case 0://同步操作：executeTransaction修改
                mRealm.executeTransaction(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        Men men = realm.where(Men.class).findFirst();
                        men.setName("我把第一个同步修改了");
                    }
                });
                break;
            case 1://异步操作：executeTransactionAsync修改
                realmAsyncTask = mRealm.executeTransactionAsync(new Realm.Transaction() {
                    @Override
                    public void execute(Realm realm) {
                        Men men = realm.where(Men.class).findFirst();
                        men.setName("我把第一个,异步修改了");
                    }
                }, new Realm.Transaction.OnSuccess() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("修改完成");
                    }
                }, new Realm.Transaction.OnError() {
                    @Override
                    public void onError(Throwable error) {
                        UIUtils.showToast("修改失败");
                    }
                });
                break;
            case 2://重要：使用查询语句得到数据，然后将内容修改
                //这里需要注意，姿势不对会出错（出现漏修改情况）
                RealmResults<Men> all = mRealm.where(Men.class)
                        .findAll();
//                mRealm.beginTransaction();
//                for (int i = 0; i < all.size(); i++) {
//                    all.get(i).setName("使用查询语句后就可以修改");
//                }
//                mRealm.commitTransaction();
                //到这里是不行的，因为迭代器修改时会移除，所以导致隔一修改情况，

                // 需要一下操作
                mRealm.beginTransaction();
                OrderedRealmCollectionSnapshot<Men> menSnapshot = all.createSnapshot();
                for (int i = 0; i < menSnapshot.size(); i++) {
                    menSnapshot.get(i).setName("使用查询语句后就可以修改!");
                }
                mRealm.commitTransaction();
                break;
        }
    }
}
